<!-- src/views/Student/Experiment.vue -->
<template>
    <ExperimentUnityWrapper @experimentData="handleExperimentData"/>
</template>

<script setup>
import { onBeforeUnmount } from 'vue'
import ExperimentUnityWrapper from '../../components/ExperimentUnityWrapper.vue'
import axios from 'axios'

// 处理 Unity 发送的数据（实验开始、步骤、结束信息）
function handleExperimentData(data) {
  axios.post('/api/experiment', data)
      .then(response => {
        console.log('数据已发送至后端', response.data)
      })
      .catch(error => {
        console.error('发送数据失败', error)
      })
}

// 页面刷新前触发，发送刷新通知给后端
function beforeUnloadHandler(event) {
  axios.post('/api/experiment/refresh')
      .then(response => {
        console.log('刷新通知发送成功', response.data)
      })
      .catch(error => {
        console.error('刷新通知发送失败', error)
      })
  event.preventDefault()
  event.returnValue = '确定刷新页面吗？刷新将结束正在进行的实验'
}

window.addEventListener('beforeunload', beforeUnloadHandler)
onBeforeUnmount(() => {
  window.removeEventListener('beforeunload', beforeUnloadHandler)
})
</script>
